﻿using AspDotNet.EasyUI.Commonlibs;
using AspDotNet.EasyUI.Models;
using AutomaticGrab.Commlibs.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspDotNet.EasyUI.Controllers
{
    public class DatagridController : Controller
    {
        // GET: Datagrid
        public ActionResult Index()
        {
            return View();
        }

        private static List<Order> Orders = new List<Order>();

        private List<Order> GetAllOrders()
        {
            if (Orders.Count < 1)
            {
                var orders = JsonConvert.DeserializeObject(System.IO.File.ReadAllText(Server.MapPath("~/resources/order.json"))) 
                    as JToken;
                Orders = orders.Cast<object>()
                    .ConvertToNewObject<List<Order>>();
            }

            return Orders;
        }

        public string GetOrdersPagging()
        {
            int page = Request.QueryString[nameof(page)].Predict("1").ToInt32();
            int rows = Request.QueryString[nameof(rows)].Predict("50").ToInt32();

            var array = GetAllOrders();

            var json=JsonConvert.SerializeObject(new
            {
                total = array.Count(),
                rows = array.Skip((page - 1) * rows).Take(rows),
            });
            return json;
        }
    }
}